<template applyReimbursement>
  <a-modal width="1300px" title="报销" :visible="value" :maskClosable="false" @cancel="onCancel(true)">
    <a-spin tip="提交中..." :spinning="isSubLoading">
      <a-steps :current="oneStep ? 0 : 1" progress-dot class="step-box">
        <a-step title="报销信息" description="" />
        <a-step title="选择报销明细" description="" />
      </a-steps>
      <!-- 报销信息 第一步 -->
      <a-row v-if="oneStep" :gutter="20">
        <a-col :span="11">
          <div class="one-box-common">
            <a-row class="onestep-box">
              <a-col :span="11" class="onestep-box-item">
                <p class="item-title">报销人：</p>
                <p class="item-content">{{ personInfo.name || '空' }}</p>
              </a-col>
              <a-col :span="7" class="onestep-box-item">
                <p class="item-title">费用类型：</p>
                <p class="item-content">抖加</p>
              </a-col>
              <a-col :span="6" class="onestep-box-item">
                <p class="item-title">款项类型：</p>
                <p class="item-content">报销</p>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="11" class="onestep-box-item">
                <p class="item-title">报销主体：</p>
                <p class="item-content">联联永创科技有限公司</p>
              </a-col>
              <a-col :span="7" class="onestep-box-item">
                <p class="item-title">打款类型：</p>
                <p class="item-content">对私</p>
              </a-col>
            </a-row>
          </div>
        </a-col>
        <a-col :span="13">
          <a-form-model class="one-box-common form-box" ref="applyModalForm" :model="applyModalForm" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
            <a-form-model-item label="大区" prop="area" class="margin-bott-20" style="margin-bottom:12px;" :rules="[{ required: true, message: '请选择大区', trigger: 'blur' }]">
              <a-select @focus="getAllAreaFun" @change="changeArea" style="width:200px;" v-model="applyModalForm.areaId" show-search :filter-option="false" allow-clear placeholder="请选择大区">
                <a-select-option v-for="(item, index) in allArea" :key="index" :areaName="item.name" :value="item.configId">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item
              label="报销金额"
              prop="money"
              :rules="[
                { required: true, trigger: 'blur', message: '请进入下一步选择报销明细' },
                {
                  pattern: /^\d+(\.\d+)?$/,
                  message: '金额格式有误',
                  trigger: 'blur'
                }
              ]"
            >
              <a-input :disabled="true" v-model="applyReimburseMoney" :maxLength="20" style="width:200px;" placeholder="请进入下一步选择报销明细"></a-input>
              <p v-if="canInputMoney" class="noreimburse-money">未报销金额：{{ canInputMoney }}</p>
            </a-form-model-item>
            <a-form-model-item
              label="发票邮寄单号"
              prop="billNo"
              :rules="[
                { required: true, message: '请输入发票邮寄单号', trigger: 'blur' },
                {
                  pattern: /^[A-Za-z0-9]+$/,
                  message: '单号格式有误',
                  trigger: 'blur'
                }
              ]"
            >
              <a-input style="width:200px;" :maxLength="20" v-model="applyModalForm.billNo" placeholder="请输入发票邮寄单号"></a-input>
            </a-form-model-item>
            <a-form-model-item label="发票开具截图" prop="billUrls" :rules="[{ required: true, message: '请上传发票开具截图', trigger: ['change', 'blur'] }]">
              <upload :limit="9" v-model="applyModalForm.billUrls"></upload>
            </a-form-model-item>
          </a-form-model>
        </a-col>
      </a-row>
      <!-- 选择报销明细 第二步 -->
      <a-row v-else class="new-box" style="padding:0;">
        <a-col :span="14" class="reimburse-wapper-com apply-money-box">
          <!-- <div class="reimburse-common">申请报销金额：￥{{ applyModalForm.money || 0 }}</div> -->
          <a-table :columns="tableColumns" :row-selection="rowSelection" :pagination="false" :data-source="expensePutDataList" rowKey="id" :scroll="{ x: 400, y: 300 }">
            <!-- 报销状态 -->
            <template slot="status" slot-scope="text, record">
              <span v-if="!record.status">未报销</span>
              <span v-else class="green-text">已报销</span>
            </template>
            <!-- 产品信息 -->
            <template slot="productId" slot-scope="text, record">
              <p>产品ID：{{ record.productId || '空' }}</p>
              <p>产品名称：{{ record.productName || '空' }}</p>
              <p>套餐ID：{{ record.productItemId || '空' }}</p>
              <p>套餐名称：{{ record.productItemName || '空' }}</p>
            </template>
            <!-- 作品信息 -->
            <template slot="videoId" slot-scope="text, record">
              <p>视频ID：{{ record.videoId || '空' }}</p>
              <p>视频链接：{{ record.videoUrl || '空' }}</p>
              <p>主播昵称：{{ record.nickName || '空' }}</p>
              <p>抖音号：{{ record.dyNo || '空' }}</p>
            </template>
            <!-- 投放信息 -->
            <template slot="putTime" slot-scope="text, record">
              <p>
                投放金额：<span class="green-text">¥{{ record.money ? (record.money / 100).toFixed(2) : 0 }}</span>
              </p>
              <p>投放时间：{{ record.putTime || '空' }}</p>
            </template>
          </a-table>
          <!-- 分页 -->
          <div class="paging-container new-paging-container">
            <a-pagination
              :pageSize="search.pageSize"
              v-model="search.pageIndex"
              :total="pageTotal"
              showQuickJumper
              showLessItems
              :showTotal="(total) => `共 ${total} 条`"
              style="margin: 10px auto;"
              @change="handlePageChange"
            />
          </div>
        </a-col>
        <a-col :span="1" class="middle-arrow">
          <a-icon type="right-square" :style="{ fontSize: '24px', color: '#ddd' }" />
        </a-col>
        <a-col :span="9" class="reimburse-wapper-com select-money-box">
          <div class="reimburse-common">已选择明细金额：￥{{ applyReimburseMoney || 0 }}</div>
          <div class="df has-selected">
            <p>已选：{{ selectItemList.length || 0 }}</p>
            <p @click="deleteItem(1)">清空</p>
          </div>
          <div class="select-list">
            <div class="select-list-item" v-for="(item, index) in selectItemList" :key="item.id">
              <div class="product-content">
                <p>产品ID：{{ item.productId || '空' }}</p>
                <a-tooltip placement="right" v-if="item.productName && item.productName.length > 8">
                  <template slot="title">
                    <div>{{ item.productName || '空' }}</div>
                  </template>
                  <p :class="{ 'ellipsis-p': item.productName && item.productName.length > 8 }">产品名称：{{ item.productName || '空' }}</p>
                </a-tooltip>
                <p v-else>产品名称：{{ item.productName || '空' }}</p>
                <p>套餐ID：{{ item.productItemId || '空' }}</p>
                <a-tooltip placement="right" v-if="item.productItemName && item.productItemName.length > 8">
                  <template slot="title">
                    <div>{{ item.productItemName || '空' }}</div>
                  </template>
                  <p :class="{ 'ellipsis-p': item.productItemName && item.productItemName.length > 8 }">套餐名称：{{ item.productItemName || '空' }}</p>
                </a-tooltip>
                <p v-else>套餐名称：{{ item.productItemName || '空' }}</p>
              </div>
              <div class="putin-content">
                <p>
                  投放金额：<span class="green-text">￥{{ item.money ? (item.money / 100).toFixed(2) : 0 }}</span>
                </p>
                <p>投放时间：{{ item.putTime || '空' }}</p>
              </div>
              <div class="action-icon flex-shrink-0" @click="deleteItem(0, item.id)"><a-icon :style="{ fontSize: '16px', color: '#b6b2b2' }" type="minus-circle" /></div>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-spin>
    <!-- 操作 -->
    <template slot="footer">
      <template style="display:flex;justify-content: center;">
        <a-button class="gray-btn border-radious-2 color-333" @click="onCancel(oneStep)">{{ oneStep ? '取消' : '上一步' }}</a-button>
        <a-button type="primary" style="background:#1D6FE9" @click="oneStep ? nextAction() : submitApply('applyModalForm')">{{ oneStep ? '下一步' : '提交审核' }}</a-button>
      </template>
    </template>
  </a-modal>
</template>
<script>
import { getAllUserList } from '@/service'
import { djReimbursementUrl, areaAllListUrl, reimbursementSelectUrl, waitReimbursementMoneyUrl } from '@/service/djService'
import upload from '@/components/upload/upload'
import debounce from 'lodash/debounce'
import { douJiaColumn } from '../column'
const g = function(item = {}) {
  return {
    putRecordIds: item.putRecordIds || [], // 报销投放记录id
    money: item.money ? (item.money / 100).toFixed(2) : '',
    id: item.id || '',
    billNo: item.billNo || '', // 发票邮寄单号
    areaId: item.areaId || '',
    area: item.area || '',
    applyUser: item.applyUser || '',
    billUrls: item.billUrls ? item.billUrls : item.billUrls || [] // 开具发票截图
  }
}

export default {
  name: 'applyReimbursement',
  props: {
    type: {
      type: Number,
      default: 0
    },
    value: {
      type: Boolean,
      default: false
    },
    getInfo: {
      type: Object,
      default: () => {}
    },
    personInfo: {
      type: Object,
      default: () => {}
    },
    getAreaList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    getInfo(val) {
      console.log(val)
      //   this.applyModalForm = detailInfo
    }
  },
  components: { upload },
  computed: {
    rowSelection() {
      const { selectedRowKeys } = this
      return {
        selectedRowKeys,
        onChange: (value, record) => this.onSelectChange(value, record),
        getCheckboxProps: (record) => ({
          // 已报销/报销中的投放记录置灰显示已报销无法勾选 是否报销0未报销,1已报销
          props: {
            disabled: record.status !== 0, // Column configuration not to be checked
            name: record.name
          }
        })
      }
    }
    // applyReimburseMoney() {
    //   const { selectItemList = [] } = this
    //   let selectMoneyList = []
    //   selectItemList.forEach((item) => {
    //     selectMoneyList.push(item.money)
    //   })

    //   if (selectMoneyList.length > 0) {
    //     let sum = 0
    //     sum = selectMoneyList.reduce(function(total, currentValue) {
    //       return total + currentValue
    //     })
    //     return sum ? (sum / 100).toFixed(2) : 0
    //   } else {
    //     return 0
    //   }
    // }
  },
  data() {
    this.getAllAreaFun = debounce(this.getAllAreaFun, 800)
    return {
      tableColumns: douJiaColumn.operatePutInDetail || [],
      userLoading: false,
      allUser: [],
      applyModalForm: g({}),
      isSubLoading: false,
      warningShow: false,
      oneStep: true,
      selectedRowKeys: [],
      dataSouce: [],
      getName: '',
      allArea: [],
      applyReimburseMoney: 0,
      search: {
        pageIndex: 1,
        pageSize: 5
      },
      pageTotal: 0,
      expensePutDataList: [],
      canInputMoney: 0,
      selectItemList: []
    }
  },
  methods: {
    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.search.pageIndex = num
      this.getList()
    },
    onSelectChange(selectedRowKeys, row) {
      this.selectedRowKeys = selectedRowKeys
      let selectRow = []
      let conformRows = []
      let selectMoney = []
      conformRows = this.selectItemList.concat(row)
      for (var i = 0; i < conformRows.length; i++) {
        if (selectRow.indexOf(conformRows[i]) === -1 && selectedRowKeys.includes(conformRows[i].id)) {
          selectRow.push(conformRows[i])
          selectMoney.push(conformRows[i].money)
        }
      }
      this.selectItemList = Array.from(selectRow)
      let selectMoneySum = selectMoney.reduce(function(total, currentValue) {
        return total + currentValue
      }, 0)
      this.applyReimburseMoney = (selectMoneySum / 100).toFixed(2)
    },
    getAllAreaFun() {
      console.log(this.getAreaList)
      if (this.getAreaList.length <= 0) {
        areaAllListUrl()
          .then((res = []) => {
            this.allArea = res
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        this.allArea = this.getAreaList
      }
    },
    changeArea(e, option = {}) {
      const { data = {} } = option || {}
      this.applyModalForm.area = data.attrs && data.attrs.areaName ? data.attrs.areaName : ''
      this.getNorReimburseMoney(this.applyModalForm.areaId)
    },
    getNorReimburseMoney(configId = '') {
      waitReimbursementMoneyUrl({ configId }).then((res = {}) => {
        console.log(res)
        this.canInputMoney = res ? (res / 100).toFixed(2) : 0
      })
    },
    getList() {
      reimbursementSelectUrl({ ...this.search, areaId: this.applyModalForm.areaId }).then((res = {}) => {
        const { expensePutDataList = [], total = 0 } = res
        console.log(res)
        this.expensePutDataList = expensePutDataList
        this.pageTotal = total
      })
    },
    onCancel(isOne = true) {
      if (isOne) {
        this.$emit('input', false)
        this.applyModalForm = g({})
        this.applyReimburseMoney = 0
        this.clearForm()
        this.selectedRowKeys = []
        this.search.pageIndex = 1
        this.canInputMoney = 0
        this.selectItemList = []
        this.oneStep = true
      } else {
        this.oneStep = false
        this.oneStep = !this.oneStep
      }
    },
    clearForm() {
      let form = this.$refs.applyModalForm
      if (form && form.clearValidate) {
        this.$nextTick(() => {
          form.clearValidate()
        })
      }
    },
    nextAction() {
      const { areaId = '', money = 0 } = this.applyModalForm || {}
      const { canInputMoney = 0 } = this
      // if (canInputMoney * 100 < money * 100) {
      //   this.$messageSend.error('报销金额超过未报销金额，请更正')
      //   return
      // }
      if (!areaId) {
        this.$messageSend.error('请选择大区')
        return
      }
      this.getList()
      this.oneStep = false
    },
    // type 0:single 1:more
    deleteItem(type = 0, id = 0) {
      const _this = this
      if (this.selectItemList.length === 0) {
        this.$messageSend.error('无数据可操作')
        return
      }
      if (type) {
        _this.selectItemList = []
        _this.selectedRowKeys = []
      } else {
        _this.selectItemList.splice(
          _this.selectItemList.findIndex((i) => i.id === Number(id)),
          1
        )
      }
      _this.selectedRowKeys.splice(_this.selectedRowKeys.indexOf(id), 1)
      // this.$confirm({
      //   title: '删除',
      //   content: `你确定要删除${type ? '所有' : '该条'}套餐报销明细吗？`,
      //   okText: '确定',
      //   okType: 'primary',
      //   onOk: () => {
      //     if (type) {
      //       _this.selectItemList[index].splice(index, 1)
      //     } else {
      //       _this.selectItemList = []
      //     }
      //   },
      //   onCancel() {}
      // })
    },
    submitApply() {
      // todo java提示还是我？点击“提交审核”校验已选择明细金额是否等于申请报销金额，不等于则toast提示“已选择投放明细金额不等于申请报销金额，请更正选择”；等于则提交审核成功，公共审批自动发起该报销申请；
      const { name } = this.personInfo
      this.applyModalForm.money = this.applyReimburseMoney
      const { areaId = 0, money = '', billNo = '', billUrls = [] } = this.applyModalForm || {}
      if (areaId && money && billNo && billUrls.length > 0) {
        this.isSubLoading = true
        djReimbursementUrl({ ...this.applyModalForm, putRecordIds: this.selectedRowKeys, money: money * 100, applyUser: name })
          .then((res) => {
            this.$emit('callback')
            this.onCancel(true)
            this.oneStep = true
          })
          .finally(() => {
            // this.$messageSend.success('提交成功')
            this.isSubLoading = false
          })
          .catch(() => {
            this.isSubLoading = false
          })
      } else {
        this.$messageSend.error('报销信息还未填写')
      }
    }
  }
}
</script>
<style scoped lang="less">
/deep/ .ant-modal-header {
  border-bottom: 1px solid transparent !important;
}
/deep/ .ant-modal-body {
  padding-top: 0;
}
/deep/ .ant-modal-footer {
  box-shadow: 0px 2px 2px 0px rgba(0, 0, 0, 0.02), inset 0px -1px 0px 0px #f5f5f5;
}
/deep/ .ant-upload-select-picture-card,
/deep/ .ant-upload-list-picture-card .ant-upload-list-item,
/deep/ .ant-upload-list-picture-card-container {
  width: 60px !important;
  height: 60px !important;
  margin: 0 3px 3px 0;
  font-size: 8px;
  .anticon-plus {
    font-size: 12px;
  }
}
/deep/ .ant-upload {
  font-size: 8px;
  color: #b8caf2;
  background: #f4f7fd;
}
.ant-modal-body {
  padding: 0;
}
.flex {
  display: flex;
  justify-content: space-between;
  /* width: 100%; */
}
.ant-form-item {
  margin-bottom: 20px;
  width: 48%;
  margin-right: 1%;
}
.ant-form-item-control {
  width: 100%;
}
</style>
<style scoped lang="scss">
.step-box {
  width: 580px;
  margin: 16px auto;
}
.image-remind {
  color: #666;
  font-size: 12px;
  height: 20px;
  margin-top: -15px;
}
.upload1 {
  position: relative;
  top: -10px;
}
.upload2 {
  margin-top: 0;
  position: relative;
  top: -10px;
}
.form-one,
.form-two {
  display: flex;
  justify-content: space-between;
  border-radius: 10px;
  padding: 15px;
  &-item {
    background: #f5f5f5;
    width: calc(100% - 70px);
    border-radius: 10px;
    padding-top: 10px;
  }
}
.form-two {
  margin: 0 10px 10px;
  padding-right: 10px;
  flex-wrap: wrap;
  &-text {
    width: 90px;
  }
  &-wapper {
    width: calc(100% - 100px);
    &-item {
      display: flex;
      justify-content: space-between;
    }
  }
  &-item {
    background: #fff;
    padding: 10px;
    margin-bottom: 5px;
    width: calc(100% - 30px);
  }
}
.remind-dian {
  margin-right: 5px;
  color: #f00;
}
.onestep-box {
  margin-bottom: 20px;
  &-item {
    .item-title {
      font-size: 12px;
      font-weight: 400;
      color: #666666;
    }
    .item-content {
      font-size: 14px;
      font-weight: bold;
      color: #333333;
    }
  }
}
.one-box-common {
  background: #f8f8f8;
  border-radius: 4px;
  padding: 20px 24px;
  height: 205px;
}

// .form-box::-webkit-scrollbar {
//   width: 1px;
//   height: 1px;
//   background-color: #b5b1b1;
// }
// //scroll轨道背景
// .form-box::-webkit-scrollbar-track {
//   -webkit-box-shadow: none;
//   border-radius: 2px;
// }
.form-box {
  display: flex;
  flex-wrap: wrap;
  overflow-y: scroll;
}
.reimburse-common {
  width: 100%;
  height: 44px;
  background: url(https://ll-oss-debug.oss-cn-beijing.aliyuncs.com/1654485863463.png) no-repeat;
  background-size: 100% 100%;
  margin-bottom: 10px;
  line-height: 44px;
  padding-left: 12px;
  font-weight: bold;
}
.reimburse-wapper-com {
  background: #f8f8f8;
  border-radius: 4px;
  font-size: 14px;
  color: #333333;
  padding: 10px 15px;
  height: 430px;
  overflow: hidden;
}
// .apply-money-box {
//   overflow-y: scroll;
//   position: relative;
// }
.select-money-box {
  overflow: hidden;
}
.apply-money-box::-webkit-scrollbar,
.select-list::-webkit-scrollbar {
  width: 1px;
  height: 1px;
  // background-color: #b5b1b1;
}
//scroll轨道背景
.apply-money-box::-webkit-scrollbar-track,
.select-list::-webkit-scrollbar-track {
  -webkit-box-shadow: none;
  border-radius: 2px;
}
.new-box .ant-table thead tr th {
  font-weight: bold;
}
.has-selected {
  justify-content: space-between;
  font-size: 14px;
  font-weight: 400;
  color: #999999;
  cursor: pointer;
  margin-bottom: 5px;
}
.middle-arrow {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 330px;
}
.select-list {
  background: #fff;
  border: 1px solid #f5f5f5;
  overflow-y: scroll;
  height: calc(100% - 78px);
  // padding: 10px 0;
  &-item {
    padding: 12px 10px 12px 16px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 13px;
    font-weight: 400;
    color: #333333;
    display: flex;
    justify-content: space-between;
    .product-content {
      width: 185px;
    }
    .putin-content,
    .product-content,
    .action-icon {
      padding-right: 10px;
      font-size: 13px;
      font-weight: 400;
      color: #333333;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      .ellipsis-p {
        width: 100%;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      p {
        margin-bottom: 3px;
      }
    }
    .action-icon {
      padding: 0;
      cursor: pointer;
    }
  }
  // &-item:first-child {
  //   padding-top: 0;
  // }
  // &-item:last-child {
  //   padding-bottom: 0;
  // }
}
.noreimburse-money {
  color: #f5894e;
  font-size: 12px;
  line-height: 1;
  margin: 0;
}
p {
  margin: 0;
  font-size: 13px;
}
</style>
